package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private ShoppingCartMapper shoppingCartMapper;
	@Autowired
	private AddressBookMapper addressBookMapper;
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private WeChatPayUtil weChatPayUtil;
	@Autowired
	private WebSocketServer webSocketServer;

	@Transactional(rollbackFor = Exception.class)
	@Override
	public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
		AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
		if (addressBook == null) {
			//TODO后面再进行优化
			throw new RuntimeException("地址有误");
		}

		List<ShoppingCart> list = shoppingCartMapper.getListByUserId(BaseContext.getCurrentId());
		if (list == null) {
			throw new RuntimeException("购物车为空");
		}

		//构建order订单
		Orders order = new Orders();
		BeanUtils.copyProperties(ordersSubmitDTO, order);
		order.setNumber(System.currentTimeMillis() + "");
		order.setStatus(1);
		order.setUserId(BaseContext.getCurrentId());
		order.setOrderTime(LocalDateTime.now());
		order.setPayStatus(0);
		order.setUserName(addressBook.getConsignee());
		order.setPhone(addressBook.getPhone());
		order.setAddress(addressBook.getDetail());
		order.setConsignee(addressBook.getConsignee());
		//TODO 后面进行调整
		order.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));
		//插入订单
		orderMapper.inset(order);

		//构建订单明细

		List<OrderDetail> orderDetailList = new ArrayList<>();
		for (ShoppingCart shoppingCart : list) {
			OrderDetail orderDetail = new OrderDetail();
			BeanUtils.copyProperties(shoppingCart, orderDetail);
			orderDetail.setOrderId(order.getId());
			//orderDetail.setImage(shoppingCart.getImage());
			//orderDetail.setName(shoppingCart.getName());
			orderDetailList.add(orderDetail);
		}

		//插入订单明细
		orderDetailMapper.insertBatch(orderDetailList);

		//删除购物车数据
		shoppingCartMapper.remove(BaseContext.getCurrentId());

		return OrderSubmitVO.builder().id(order.getId()).orderNumber(order.getNumber()).orderAmount(order.getAmount()).orderTime(order.getOrderTime()).build();

	}

	//@Override
	//public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
	//
	//	orderMapper.updateStatus(ordersPaymentDTO);
	//	return null;
	//}

	/**
	 * 订单支付
	 *
	 * @param ordersPaymentDTO 订单支付参数
	 * @return 订单支付结果
	 */
	public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
		// 当前登录用户id
		Long userId = BaseContext.getCurrentId();
		User user = userMapper.getById(userId);

		//调用微信支付接口，生成预支付交易单
		//JSONObject jsonObject = weChatPayUtil.pay(
		//		ordersPaymentDTO.getOrderNumber(), //商户订单号
		//		new BigDecimal("0.01"), //支付金额，单位 元
		//		"苍穹外卖订单", //商品描述
		//		user.getOpenid() //微信用户的openid
		//);
		//跳过微信支付
		JSONObject jsonObject = new JSONObject();

		if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
			throw new OrderBusinessException("该订单已支付");
		}

		OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
		vo.setPackageStr(jsonObject.getString("package"));
		//修改订单状态，从待支付到待派送
		paySuccess(ordersPaymentDTO.getOrderNumber());
		return vo;
	}

	/**
	 * 支付成功，修改订单状态
	 *
	 * @param outTradeNo 微信支付成功返回的订单号
	 */
	public void paySuccess(String outTradeNo) {
		// 当前登录用户id
		Long userId = BaseContext.getCurrentId();

		// 根据订单号查询当前用户的订单
		Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

		// 根据订单id更新订单的状态、支付方式、支付状态、结账时间
		Orders orders = Orders.builder().id(ordersDB.getId()).status(Orders.TO_BE_CONFIRMED).payStatus(Orders.PAID).checkoutTime(LocalDateTime.now()).build();

		log.info("订单支付成功，订单号：{}", outTradeNo);
		orderMapper.update(orders);
		//通过WebSocket实现来单提醒，向客户端浏览器推送消息
		Map<String, Object> map = new HashMap<>();
		//消息类型，1表示来单提醒 2表示用户催单
		map.put("type", 1);
		map.put("orderId", orders.getId());
		map.put("content", "订单号:" + outTradeNo);
		webSocketServer.sendToAllClient(JSON.toJSONString(map));
	}

	@Override
	public PageResult historyList(Integer pageSize, Integer page, Integer status) {
		PageHelper.startPage(page, pageSize);
		OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
		ordersPageQueryDTO.setStatus(status);
		ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

		Page<Orders> list = orderMapper.list(ordersPageQueryDTO);

		List<OrderVO> orderVOList = new ArrayList<>();
		if (list != null && !list.isEmpty()) {
			for (Orders orders : list) {
				Long orderId = orders.getId();
				// 查询订单明细
				List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
				OrderVO orderVO = new OrderVO();
				BeanUtils.copyProperties(orders, orderVO);
				orderVO.setOrderDetailList(orderDetails);

				orderVOList.add(orderVO);
			}
		}

		return new PageResult(list == null ? 0 : list.getTotal(), orderVOList);
	}

	@Override
	public OrderVO orderDetail(Long id) {
		Orders order = orderMapper.getById(id);
		List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(order.getId());
		OrderVO orderVO = new OrderVO();
		BeanUtils.copyProperties(order, orderVO);
		orderVO.setOrderDetailList(orderDetailList);
		return orderVO;
	}

	@Override
	public void repetition(Long id) {
		Long userId = BaseContext.getCurrentId();
		List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

		List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
			ShoppingCart shoppingCart = new ShoppingCart();
			BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
			shoppingCart.setUserId(userId);
			shoppingCart.setCreateTime(LocalDateTime.now());
			return shoppingCart;
		}).toList();
		shoppingCartMapper.insertBatch(shoppingCartList);
	}

	@Override
	public void cancel(Long id) throws Exception {
		Orders ordersDB = orderMapper.getById(id);
		if (ordersDB == null) {
			throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
		}
		//订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
		if (ordersDB.getStatus() > 2) {
			throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
		}

		Orders orders = new Orders();
		orders.setId(ordersDB.getId());

		//测试跳过微信退款逻辑
		// 订单处于待接单状态下取消，需要进行退款
		//if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
		//	//调用微信支付退款接口
		//	weChatPayUtil.refund(
		//			ordersDB.getNumber(), //商户订单号
		//			ordersDB.getNumber(), //商户退款单号
		//			new BigDecimal("0.01"),//退款金额，单位 元
		//			new BigDecimal("0.01"));//原订单金额
		//}

		//支付状态修改为 退款
		orders.setPayStatus(Orders.REFUND);
		orders.setStatus(Orders.CANCELLED);
		orders.setCancelReason("用户取消");
		orders.setCancelTime(LocalDateTime.now());
		orderMapper.update(orders);
	}

	/**
	 * 用户催单
	 *
	 * @param id 订单id
	 */
	@Override
	public void reminder(Long id) {
		Orders orders = orderMapper.getById(id);
		if (orders == null) {
			throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
		}
		Map<String, Object> map = new HashMap<>();
		map.put("type", 2);
		map.put("orderId", id);
		map.put("content", "订单号：" + orders.getNumber());
		webSocketServer.sendToAllClient(JSON.toJSONString(map));
	}

	@Override
	public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
		PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
		Page<Orders> page = orderMapper.list(ordersPageQueryDTO);

		List<OrderVO> orderVOList = getOrderVOS(page);
		return new PageResult(page.getTotal(), orderVOList);
	}

	@Override
	public OrderStatisticsVO statistics() {
		return orderMapper.statistics();
	}

	@Override
	public void confirm(OrdersDTO ordersDTO) {
		Orders orders = new Orders();
		BeanUtils.copyProperties(ordersDTO, orders);
		orders.setStatus(Orders.CONFIRMED);
		orderMapper.update(orders);
	}

	@Override
	public void delivery(Long id) {
		Orders orders = orderMapper.getById(id);
		if (orders == null || !Objects.equals(orders.getStatus(), Orders.CONFIRMED)) {
			throw new RuntimeException("订单不存在，或者订单状态有误");
		}
		orders.setId(id);
		orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
		orderMapper.update(orders);
	}

	@Override
	public void complete(Long id) {
		Orders orders = orderMapper.getById(id);
		if (orders == null || !Objects.equals(orders.getStatus(), Orders.DELIVERY_IN_PROGRESS)) {
			throw new RuntimeException("订单不存在，或者订单状态有误");
		}
		orders.setId(id);
		orders.setStatus(Orders.COMPLETED);
		orderMapper.update(orders);
	}

	@Override
	public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
		Orders orders = new Orders();
		//orders.setId(ordersRejectionDTO.getId());
		BeanUtils.copyProperties(ordersRejectionDTO, orders);
		orders.setStatus(Orders.CANCELLED);
		orderMapper.update(orders);
	}

	@Override
	public void adminCancel(Orders orders) {
		orders.setStatus(Orders.CANCELLED);
		orderMapper.update(orders);
	}

	private static List<OrderVO> getOrderVOS(Page<Orders> page) {
		List<OrderVO> orderVOList = new ArrayList<>();
		List<Orders> ordersList = page.getResult();
		if (ordersList != null && !ordersList.isEmpty()) {
			for (Orders orders : ordersList) {
				OrderVO orderVO = new OrderVO();
				BeanUtils.copyProperties(orders, orderVO);
				orderVOList.add(orderVO);
			}
		}
		return orderVOList;
	}

}
